package fun.diaoer.mapper.base;

import java.sql.Date;
import java.sql.Timestamp;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.SelectProvider;

import ch.qos.logback.classic.pattern.MessageConverter;
import fun.diaoer.entity.BaseEntity;
import fun.diaoer.exception.GenericException;
import fun.diaoer.mapper.provider.DIBaseDeleteProvider;
import tk.mybatis.mapper.annotation.RegisterMapper;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.common.ConditionMapper;
@RegisterMapper
public interface DIBaseMapper<T> extends BaseMapper<T>, ConditionMapper<T>{
	
	/**
	 * 获取数据库当前时间
	 */
	@SelectProvider(type = DIBaseDeleteProvider.class, method = "dynamicSQL")
	Date getDatabaseDate();

	@SelectProvider(type = DIBaseDeleteProvider.class, method = "dynamicSQL")
	Timestamp getDatabaseTimestamp();
	
	/**
	 * 仅根据主键删除（无乐观锁）
	 */
	@DeleteProvider(type = DIBaseDeleteProvider.class, method = "dynamicSQL")
	int deleteById(String id);
	
	/**
	 * 通过主键删除（乐观锁-MAPPER新版本删除不支持乐观锁了）
	 */
	@DeleteProvider(type = DIBaseDeleteProvider.class, method = "dynamicSQL")
	int deleteByPrimaryKey2(Object record);
	
	/**
	 * 更新（乐观锁）
	 */
	default int updateByPrimaryKeyWithVer(T record) {
		int i = this.updateByPrimaryKey(record);
		if (i == 0) {
			throw new GenericException("乐观锁异常");
		}
		// 返回对象版本号+1
		else if (record instanceof BaseEntity) {
			((BaseEntity) record).setRecVer((((BaseEntity) record).getRecVer() == null ? 0 : ((BaseEntity) record).getRecVer()) + 1);
		}
		return i;
	}

	/**
	 * 更新（乐观锁）
	 */
	default int updateByPrimaryKeySelectiveWithVer(T record) {
		int i = this.updateByPrimaryKeySelective(record);
		if (i == 0) {
			throw new GenericException("乐观锁异常");
		}
		// 返回对象版本号+1
		else if (record instanceof BaseEntity) {
			((BaseEntity) record)
					.setRecVer((((BaseEntity) record).getRecVer()== null ? 0 : ((BaseEntity) record).getRecVer()) + 1);
		}
		return i;
	}

	/**
	 * 删除（乐观锁）
	 */
	default int deleteByPrimaryKeyWithVer(Object key) {
		// 只根据主键删除（无乐观锁）
		if (key instanceof String) {
			return deleteById((String) key);
		}

		int i = this.deleteByPrimaryKey2(key);
		if (i == 0) {
			throw new GenericException("乐观锁异常");
		}
		return i;
	}

	/**
	 * 删除（乐观锁）
	 */
	default int deleteWithVer(T record) {
		int i = this.delete(record);
		if (i == 0) {
			throw new GenericException("乐观锁异常");
		}
		return i;
	}

}
